package com.justech.tcp.server;

import com.alibaba.fastjson.JSONObject;
import com.justech.tcp.server.parse.EquipmentInfo;
import com.justech.tcp.server.parse.EquipmentInfoParser;
import com.justech.tcp.server.parse.Parser;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @ClassName
 * @Author: xiaofeng.yang
 * @Date: Create in 15:36 2019/11/29
 * @Description : TODO
 * @Version: 1.0
 */
public class SimpleChannelHandler extends ChannelInboundHandlerAdapter {
    private static  final Logger logger= LoggerFactory.getLogger(SimpleChannelHandler.class);
    private Channel channel;
    private Sender sender;
    private Receiver receiver;
    private String key;

    public SimpleChannelHandler() throws IOException, TimeoutException {
        sender = Sender.getInstance();
        receiver = new Receiver();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("tcp channel active:{}",ctx.channel().remoteAddress());
        super.channelActive(ctx);
        this.channel = ctx.channel();
        key = ipPath(this.channel.remoteAddress().toString());
        receiver.binding(key);
        receiver.receive(this.channel);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("tcp channel close:{}",ctx.channel().remoteAddress());
        super.channelInactive(ctx);
        receiver.close();

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf in = ((ByteBuf) msg);
        String s = in.toString(io.netty.util.CharsetUtil.US_ASCII);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("key", key);
        if (vaildData(s, jsonObject)) {
            try {
                sender.send(jsonObject.toJSONString());
            } catch (IOException e) {
                logger.error("channelRead:",e);
                ByteBuf out = Unpooled.copiedBuffer("@Wrong", CharsetUtil.UTF_8);
                this.channel.writeAndFlush(out);
            }
        } else {
            ByteBuf out = Unpooled.copiedBuffer("@Wrong", CharsetUtil.UTF_8);
            this.channel.writeAndFlush(out);
        }
        in.release();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    private String ipPath(String s) {
        return s.split(":")[0].replaceAll("/", "").replaceAll("\\.", "");
    }

    private boolean vaildData(String s, JSONObject jsonObject) {
        Parser parser = new EquipmentInfoParser();
        try {
            EquipmentInfo equipmentInfo = parser.parse(s);
            jsonObject.put("data", equipmentInfo.toString());
        } catch (Exception e) {
            logger.error("vaildData:",e);
            return false;
        }
        return true;
    }
}
